<?php

class SiteController extends Controller
{
	public $layout = 'awt-public';
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}
	
	public function filters() {
		return array(
			'accessControl',
		);
	}
		
	public function accessRules() {
		
		//$isAdmin = "isset(Yii::app()->user->role) && (Yii::app()->user->role==='admin')";
		return array(
			array(
				'allow',
				'actions'=>array('login','logout','signup','page','captcha','error','res'),
				'users'=>array('*')
			),array(
				'allow',
				'users'=>array('@')
			),array(
				'deny',
				'users'=>array('?')
			),
		);
	}
	
	public function actionAccount()
	{
		$this->render('account');
	}

	public function actionIndex()
	{
		
		#$this->redirect(array('admin/searchSong'));
		
		$this->layout = 'awt';
		$this->render('index');
	}
	
	public function actionLogin()
	{
		$this->layout = 'awt-public';
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{

			$_POST['LoginForm']['pwd'] = sha1($_POST['LoginForm']['pwd'].Yii::app()->params['salt']);
			$model->attributes=$_POST['LoginForm'];
			
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$_POST['LoginForm']['pwd'] = '';
		$model->attributes=$_POST['LoginForm'];
		
		$this->render('login',array('model'=>$model));
	}

	public function actionLogout()
	{
		$this->_logout();
	}
	
	private function _logout($msg='Logout successfully, you need to login again to continue') {
		Yii::app()->user->logout();
		Yii::app()->session->open();
		Yii::app()->user->setFlash('success',$msg);
		$this->redirect(Yii::app()->user->loginUrl);
	}

	public function actionSignup()
	{
		$model = new User('signup');

		if (isset($_POST['User']) && !empty($_POST['User'])) {
			
			$pwd 			= $_POST['User']['pwd'];
			$pwdconfirm 	= $_POST['User']['pwd_confirm'];
			
			$_POST['User']['user_group_id'] 	= 2;
			$_POST['User']['user_status_id'] 	= 1;
			$_POST['User']['created']			= date('Y-m-d H:i:s');
			
			$_POST['User']['pwd']				= sha1($_POST['User']['pwd'].Yii::app()->params['salt']);
			$_POST['User']['pwd_confirm']		= sha1($_POST['User']['pwd_confirm'].Yii::app()->params['salt']);
			
			$model->attributes = $_POST['User'];
			
			if ( $model->save() ) {
				
				Yii::app()->user->setFlash('success',"成功注册了～请登入～");
				$this->redirect(Yii::app()->user->loginUrl);
				
			} else {
				echo "<pre>"; print_r( $model->getErrors() ); exit;
				Yii::app()->user->setFlash('error',"Data Not Saved");
			}
			
			$_POST['User']['pwd'] 			= $pwd;
			$_POST['User']['pwd_confirm']	= $pwdconfirm;
			$model->attributes = $_POST['User'];
		}
		$this->render('signup',array('model'=>$model));
	}
	public function actionError()
	{
		$this->layout='awt-error';
		if($error=Yii::app()->errorHandler->error)
		{
			if(Yii::app()->request->isAjaxRequest)
				echo $error['message'];
			else
				$this->render('error', $error);
		}
	}
	
	public function actionRes() {
		
		# translate
		/*
		$bp = dirname(Yii::app()->basePath).'/res/Translated_query_result.csv';
		$c = file_get_contents($bp);
		$r = explode("\n",$c);
		foreach ($r as $key => $row) {
			if (!empty($row)) {
				$rs = explode(',',$row);
				if ($rs[0]!=$rs[1]) {
					echo 'UPDATE song SET `name`='.$rs[1].' WHERE `name`='.$rs[0].';<br/>';
				}
			}
		}
		exit('');
		*/
		
		# import excel
		$phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');

		// Turn off our amazing library autoload 
		spl_autoload_unregister(array('YiiBase','autoload'));		   

		//
		// making use of our reference, include the main class
		// when we do this, phpExcel has its own autoload registration
		// procedure (PHPExcel_Autoloader::Register();)
		include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
	
		$objPHPExcel = PHPExcel_IOFactory::load("res/awt_demo2.xlsx");
		$rs = $objPHPExcel->getSheet(7)->toArray();
		//echo "<pre>"; print_r( $rs ); exit;
		$bid = 83;
		foreach ($rs as $key => $row) {
			
			### hillsong album and song together
			
			if (!empty($row[0])) {
				$bid++;
				#create new album
				echo 'INSERT INTO `album` (`name`,`year`,`tags`,`artist_id`,`user_create`,`date_create`,`album_status_id`) VALUES '.
				'("'.$row['2'].'","'.$row['4'].'","'.$row['8'].'","'.$row['0'].'","1",NOW(),"1");<br/>';
			}
			
			
			
			####
			
			//echo "<pre>"; print_r( $row ); exit;
			//if ( !empty($row['5'])) {
				/*
				$s = explode( '.',$row['4'] );
				if (count($s)>1) {
					if (strlen($s['0'])>2) {
						echo "<pre>"; var_dump( strlen($s['0']) ); exit;
						exit('a');
					}
				}
				*/
				/*
				$name = trim($row['6']) ;
				#echo $row['2'].' - '.$row['3'].'. '.$name.'<br/>';
				$user = 1;
				$lang = 1;
				switch ($row['8']) {
					case 'wy':
					$user = '10';
						break;
					case 'jiamin':
					$user = '14';
						break;
					default:
					$user = '1';
						break;
				}
				
				switch ($row['3']) {
					case 'en':
						$lang = '2';
					break;
						$lang = '1';
					default:
						$lang = '2';
					break;
				}
				echo 'INSERT INTO `song` (`album_id`,`track_no`,`name`,`lang`,`date_create`,`user_create`) VALUES '.
				'("'.$bid.'","'.$row['5'].'","'.$name.'",'.$lang.',NOW(),"'.$user.'");<br/>';
				*/
			//}
		}
		exit();
		echo "<pre>"; print_r( $rs ); exit;
		
	}
	
}